package com.qianzhou.sqlSession.impl;

import com.qianzhou.pojo.Configuration;
import com.qianzhou.pojo.MappedStatement;
import com.qianzhou.sqlSession.SqlSession;

import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName DefaultSession
 * @Description TODO
 * @Author zhouqian
 * @Date 2022/1/15 9:03 PM
 * @Version 1.0
 */

public class DefaultSession implements SqlSession {
    private Configuration configuration;
    private SimpleExecutor simpleExecutor;

    public DefaultSession(Configuration configuration) {
        this.configuration = configuration;
    }

    public <E> List<E> selectList(String statementid, Object... params) throws Exception {
        //将要去完成对simpleExecutor里的query方法的调用
        simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatement().get(statementid);
        List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);
        return (List<E>) list;
    }

    public <T> T selectOne(String statementid, Object... params) throws Exception {
        List<Object> objects = selectList(statementid, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空或者返回结果过多");
        }
    }

    @Override
    public void close() throws SQLException {
        simpleExecutor.close();
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        T o = (T) Proxy.newProxyInstance(mapperClass.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // proxy当前代理对象的应用
                // method当前被调用方法的引用
                // args传递的参数
                String methodName = method.getName();
                // className:namespace
                String className = method.getDeclaringClass().getName();
                //statementid  -- 拿到对应的namespace和id的值
                String key = className + "." + methodName;
                MappedStatement mappedStatement = configuration.getMappedStatement().get(key);
                // 被调用方法的返回值类型
                Type genericReturnType = method.getGenericReturnType();
                //判断是否实现泛型类型参数化
                if (genericReturnType instanceof ParameterizedType) {
                    return selectList(key, args);
                }
                return selectOne(key, args);
            }
        });
        return o;
    }
}
